<template>
  <div class="system-user-dialog-container">
    <el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.title" width="1000px">
      <el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="rules" label-width="100px" size="default">
        <el-row :gutter="35">
          <el-col :span="8" class="mb20">
            <el-form-item label="仓库" prop="stockTypeId">
              <el-select v-model="state.ruleForm.stockTypeId"
                         clearable
                         placeholder="请选择仓库"
                         size="default">
                <el-option
                    v-for="item in state.stockType"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb20">
            <el-form-item label="品牌" prop="supplierId">
              <el-select v-model="state.ruleForm.supplierId"
                         clearable
                         placeholder="请选择品牌"
                         size="default">
                <el-option
                    v-for="item in state.supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8" class="mb20">
            <el-form-item label="入库类型" prop="inType">
              <el-select v-model="state.ruleForm.inType"
                         clearable
                         placeholder="请选择入库类型"
                         size="default">
                <el-option
                    v-for="item in state.inTypeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-upload
            :auto-upload="false"
            :limit="1"
            :multiple="false"
            :on-change="handleFileChange"
            accept=".xlsx, .xls"
            drag
            style="text-align: center;"
        >
          <el-icon>
            <ele-Upload/>
          </el-icon>
          <div class="el-upload__text">
            将文件拖拽到此处或<em>点击上传</em>
          </div>
          <template v-slot:tip>
            <div class="el-upload__tip">请使用正确的模板上传</div>
          </template>
        </el-upload>
        <div v-show="state.uploadErrorMsg" class="upload-msg">
          <div class="title">问题数据详情</div>
          <el-alert
              v-for="item in state.uploadErrorMsg.split(';')"
              v-show="item"
              :key="item"
              :closable="false"
              :title="item"
              effect="dark"
              show-icon
              style="margin-bottom: 5px;"
              type="warning"
          />
        </div>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button v-show="!state.uploadId" size="default" type="primary" @click="uploadFile(userDialogFormRef)">
						上 传
					</el-button>
          <el-button v-show="state.uploadId" size="default" type="primary" @click="confirmUpload('true')">
						新增商品并入库
					</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="systemUserDialog" setup>
import {nextTick, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, FormRules} from 'element-plus';
import {stockTypeApi} from "/@/api/store/stock/type";
import {supplierApi} from "/@/api/store/commodity/supplier";
import {stockInApi} from "/@/api/store/stock/in";
import {dictDataApi} from "/@/api/sys/dictData";
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    stockTypeId: '', // 分类名称
    supplierId: '', // 品牌
    inType: '', // 品牌
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  uploadErrorMsg: '',
  uploadId: '',
  stockType: [],
  supplierList: [],
  inTypeList: [],
  fileList: [],
});
const rules = reactive<FormRules>({
  stockTypeId: [{required: true, message: '不能为空', trigger: 'blur'}],
  supplierId: [{required: true, message: '不能为空', trigger: 'blur'}],
  inType: [{required: true, message: '不能为空', trigger: 'blur'}],
});
// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  if (type === 'edit') {
    state.dialog.title = '修改商品';
    state.dialog.submitTxt = '修 改';
  } else if (type === 'add') {
    state.dialog.title = '上传商品入库';
    state.dialog.submitTxt = '上 传';
  }
  nextTick(() => {
    if (type === 'add') {
      // 清空表单，此项需加表单验证才能使用
      userDialogFormRef.value.resetFields();
    } else {
      state.ruleForm = Object.assign(state.ruleForm, row);
    }
  });
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

const handleFileChange = (file: any, fileList: any) => {
  state.fileList = fileList
}

// 提交
const confirmUpload = (type: any) => {
  ElMessageBox.confirm(`是否确认导入?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    stockInApi().saveUploadData(state.uploadId, type).then(res => {
      ElMessage.success(res.msg || "导入成功");
      closeDialog();
      emit('refresh');
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const uploadFile = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let fd = new FormData()
      if (state.fileList.length > 0) {
        fd.append('file', state.fileList[0].raw)
        fd.append('stockTypeId', state.ruleForm.stockTypeId)
        fd.append('supplierId', state.ruleForm.supplierId)
        fd.append('inType', state.ruleForm.inType)
        stockInApi()
            .upload(fd)
            .then(res => {
              // 如果res.data为空，说明导入没有问题数据，直接执行导入操作
              if (res.data) {
                state.uploadErrorMsg = res.data.errMsg
                state.uploadId = res.data.uploadId
                if (res.data.status === 'success') {
                  ElMessage.success("上传数据成功");
                  closeDialog();
                  emit('refresh');
                }
              }
            })
      }
    }
  })
}

// 页面加载时
onMounted(() => {

  // 仓库数据
  stockTypeApi()
      .findAll()
      .then(res => {
        state.stockType = res.data;
      })

  // 品牌
  supplierApi()
      .findAll()
      .then(res => {
        state.supplierList = res.data;
      })

  // 入库类型
  dictDataApi()
      .getDictByType("in_type")
      .then(res => {
        state.inTypeList = res.data;
      })
});

// 暴露变量
defineExpose({
  openDialog,
});
</script>
